package com.xxl.job.executor.utils;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.*;


public class CmUtil {
    private static final String REQUEST_USER_ATTRIBUTE = "REQUEST_USER_ATTRIBUTE";
    private static final String REQUEST_USER_POSITION_ATTRIBUTE = "REQUEST_USER_POSITION_ATTRIBUTE";
    private static final String REQUEST_USER_ROLE_ATTRIBUTE = "REQUEST_USER_ROLE_ATTRIBUTE";
    private static final String simpleDateFormat = "yyyy-MM-dd HH:mm:ss:SSS";
    private static final String simpleDate2day = "yyyy-MM-dd";
    protected final static Logger LOGGER = LoggerFactory.getLogger(CmUtil.class);
    // 这种方式报空指针，去除
    // @Value("${city.defaultUser.role.id}")
    // private static String defaultUserId;

    public static String date2db(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(simpleDateFormat);
        return date == null ? dateFormat.format(new Date()) : dateFormat.format(date);
    }

    public static String date2day(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(simpleDate2day);
        return date == null ? dateFormat.format(new Date()) : dateFormat.format(date);
    }

    public static String getUUID() {
        return UUID.randomUUID().toString();
    }


    public static UserModel getRequestUserModel() {
        return (UserModel) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getAttribute(REQUEST_USER_ATTRIBUTE);
    }

    public static SysUserPosition[] getRequestUserPositions() {
        return (SysUserPosition[]) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getAttribute(REQUEST_USER_POSITION_ATTRIBUTE);
    }

    public static void setRequestUserModelPosions(UserModel userModel, SysUserPosition[] array, List<String> roleList) {
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().setAttribute(REQUEST_USER_ATTRIBUTE, userModel);
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().setAttribute(REQUEST_USER_POSITION_ATTRIBUTE, array);
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().setAttribute(REQUEST_USER_ROLE_ATTRIBUTE, roleList);
    }

    public static List<String> getRequestUserRoles() {
        return (List<String>) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getAttribute(REQUEST_USER_ROLE_ATTRIBUTE);
    }

    public static String getUserId() {
        UserModel userModel = getRequestUserModel();
        if (userModel == null) {
            // 添加getUserId中返回“”的提示
            LOGGER.info("用户登录信息获取异常");
            return "";  // 开发阶段默认用户ID， 生产环境 需要重新评估
        }
        return userModel.getUserId();
    }

    /**
     * 获取本机IP
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static List<String> getLocalIP() {
        List<String> ips = new ArrayList<String>();
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            if (allNetInterfaces == null)   return ips;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        String ipAddress = ip.getHostAddress();
                        if (StringUtils.equals(ipAddress, "127.0.0.1") || ipAddress.startsWith("0")) {
                            continue;
                        }
                        ips.add(ipAddress);
                    }
                }
            }
        } catch (SocketException e) {
            LOGGER.error("获取本机ip异常", e);
        }
        return ips;
    }

    /**
     * @method  isHasDataOauth
     * @description 验证当前登录用户是否拥有dataOauthCode对应的数据权限
     * @date: 2020/3/19
     * @Param: [dataOauthCode]
     * @return  boolean    返回true 表示拥有dataOauthCode的权限
     */
//    public static boolean isHasDataOauth(String dataOauthCode){
//        boolean hasOauth = false;
//        RestTemplate restTemplate = SpringContextHolder.restTemplate;
//        String userId = getRequestUserModel().getUserId();
//        List<String> dataAuthArray = restTemplate.getForObject("http://service-sys/PUBLICS/role/getDataOauth/" + userId, List.class);
//        if(!dataAuthArray.isEmpty()){
//            if(dataAuthArray.contains(dataOauthCode)){
//                hasOauth = true;
//            }
//        }
//        return hasOauth;
//    }

}
